package zut.edu.cs.network.io.object;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import zut.edu.cs.network.io.Person;

public class ObjectStreamDemo {

	public static void main(String[] args) {
		
		Person person = new Person();
//		age无论如何修改，输出的值都将是0
		person.age = 18;
		person.name = "sweet";
//	此时的china是一个静态属性，属于类不属于对象，所以在person调用的时候会出现警告。应该用类名进行调用
		Person.country = "China";
		
		write(person);
//	此时修改的名字并不会被改变，但是国家会发生改变
//	因为name是被进行发序列化的，是读取的文件里的内容，是无法修改的。
		person.name = "xiao";
		person.country = "uk";
		read();

	}
	
	public static void read() {
		try {
			FileInputStream fileInputStream = new FileInputStream("person1.txt");
			ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
			
			Person person = (Person)objectInputStream.readObject();
			System.out.println(person);
			objectInputStream.close();
			fileInputStream.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void write(Person person) {
		File file = new File("person1.txt");
		FileOutputStream file1;
		try {
			file1 = new FileOutputStream(file);
			ObjectOutputStream os = new ObjectOutputStream(file1);
			
		/*	Person person = new Person();
//			age无论如何修改，输出的值都将是0
			person.age = 18;
			person.name = "sweet";
//		此时的china是一个静态属性，属于类不属于对象，所以在person调用的时候会出现警告。应该用类名进行调用
			Person.country = "China";*/
			os.writeObject(person);
			
			os.close();
			file1.close();
			System.out.println("写入成功");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
